﻿using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
using UnityEngine.UIElements;

namespace XFFSM
{
    public class ListenerFile
    {


        [InitializeOnLoadMethod]
        private static void InitOnLoad() {
            //Debug.Log("Init");
            Selection.selectionChanged += OnSelectionChange;


            EditorApplication.quitting += OnEditorApplicationQuitting;
        }

        private static void OnSelectionChange() 
        {
            RuntimeFSMController controller = Selection.activeObject as RuntimeFSMController;
            if (controller != null)
            {
                // 把InstanceID设置为空
                Context.Instance.FSMControllerInstanceID = 0;
                // 设置给Context 保存起来
                string assetPath = AssetDatabase.GetAssetPath(controller);
                string guid = AssetDatabase.AssetPathToGUID(assetPath);
                Context.Instance.RuntimeFSMControllerGUID = guid;
            }
            else 
            {
                GameObject gameObj = Selection.activeGameObject;
                if (gameObj == null || gameObj.activeInHierarchy == false) return;
                // 判断有没有FSMController组件
                FSMController fsmController = gameObj.GetComponent<FSMController>();
                if (fsmController == null) return;
                Context.Instance.RuntimeFSMControllerGUID = string.Empty;
                Context.Instance.FSMControllerIndex = 0;
                Context.Instance.FSMControllerInstanceID = gameObj.GetInstanceID(); 
            } 
        }

        private static void OnEditorApplicationQuitting() {
            Context.Instance.FSMControllerIndex = 0;
            Context.Instance.FSMControllerInstanceID = 0;
        }

        [UnityEditor.Callbacks.OnOpenAsset(0)]
        private static bool OnOpenAsset(int insId, int line)
        {
            RuntimeFSMController obj = EditorUtility.InstanceIDToObject(insId) as RuntimeFSMController;
            if (obj != null) 
            {
                EditorWindow.GetWindow<FSMEditorWindow>().Show();
            }
            return obj != null;
        }
    }
}

